package app

import (
	"server/pkg/setting"
	"server/utils"

	"github.com/gin-gonic/gin"
)

type Page struct {
	// 页码
	Page int `json:"page"`
	// 每页数量
	Size int `json:"page_size"`
	// 总行数
	Total int    `json:"total"`
	Sort  string `json:"sort"`
	Param map[string]interface{}
}

func (page *Page) Info(c *gin.Context) {
	page.Page = GetPage(c)
	page.Size = GetPageSize(c)
	page.Sort = c.Query("sort")
	page.Param = make(map[string]interface{})

	params := c.Request.URL.Query()
	for key, values := range params {
		if len(values) > 0 {
			v := values[0]
			page.Param[key] = v
		}
	}
}

func GetPage(c *gin.Context) int {
	page := utils.StrTo(c.Query("page")).MustInt()
	if page <= 0 {
		return 1
	}
	return page
}

func GetPageSize(c *gin.Context) int {
	pageSize := utils.StrTo(c.Query("page_size")).MustInt()
	if pageSize <= 0 {
		return setting.App.DefaultPageSize
	}
	if pageSize > setting.App.MaxPageSize {
		return setting.App.MaxPageSize
	}

	return pageSize
}

func GetPageOffset(page, pageSize int) int {
	result := 0
	if page > 0 {
		result = (page - 1) * pageSize
	}
	return result
}
